import {
  getContainerList,
  getHierachyTopoContainerDetail,
  getHierachyTopoNamespaceDetail,
  getHierachyTopoNodeDetail,
  getHierachyTopoPodDetail,
  getHierachyTopoServiceDetail,
  getHierachyTopoWorkloadDetail,
  getK8sYaml,
} from "@/api/topoNodeDetail";
import { isNumber,forEach, some, toLower } from "lodash";
import { ref, watch } from "vue";
import {
  workloadFields,
  serviceField,
  podFields,
  namespaceFields,
  nodeFields,
  containerFields,
} from "./staticData";
import { formatUnit } from "@/utils/format";

export default function useFieldInfo({
  node: nodeInfo,
  queryTime,
  getPodEventData,
}) {
  const containerList = ref([]);
  const allContainer = ref([]);
  const fieldInfo = ref([]);
  // table搜索公共函数
  const handleTableSearch = (list, value, ...fields) => {
    let result = [];
    if (value.length > 0) {
      forEach(list, (item) => {
        if (
          some(
            fields,
            (field) =>
              item[field] &&
              toLower(item[field]).indexOf(toLower(value)) > -1
          )
        ) {
          result.push(item);
        }
      });
    } else {
      result = [].concat(list);
    }
    return result;
  };
  // 搜索container
  const filterContainer = (value) => {
    const list = handleTableSearch(allContainerList, value, "name");
    containerList.value = list;
  };
  // 资源基础字段赋值吃力
  const fieldListHandle = (list, data) => {
    const node = nodeInfo.value;
    const result = [...list];
    forEach(result, (item) => {
      item.value =
        data[item.dataIndex] || isNumber(data[item.dataIndex])
          ? item.unit
            ? formatUnit(data[item.dataIndex], item.unit)
            : data[item.dataIndex]
          : "--";
      if (node[item.dataIndex]) {
        // if (item.dataIndex === 'status') {
        //     item.value = transformStatus(node[item.dataIndex])
        // } else {
        item.value = node[item.dataIndex];
        // }
      }
    });
    // console.log(result, 'result');

    return result;
  };
  // 获取资源节点的基本信息字段
  const getFieldList = () => {
    const { from, to } = queryTime.value;
    const node = nodeInfo.value;
    // console.log(node.type, "type");
    let list = [];
    switch (node.type) {
      case "namespace":
        getHierachyTopoNamespaceDetail({
          masterIp: node.masterIp,
          namespace: node.name,
          from,
          to,
        }).then((res) => {
          console.log(list, 'list');

          list = fieldListHandle(namespaceFields, res.data);
          console.log(list, 'list after handle');
          fieldInfo.value = list;
        });
        break;
      case "container":
        getHierachyTopoContainerDetail({
          masterIp: node.masterIp,
          namespace: node.namespace,
          containerName: node.name,
          podName: node.masterName,
          sid: node.sid,
          from,
          to,
        }).then((res) => {
          list = fieldListHandle(containerFields, res.data);
          fieldInfo.value = list;
        });
        break;
      case "node":
        getHierachyTopoNodeDetail({
          masterIp: node.masterIp,
          nodeIp: node.ip,
          from,
          to,
        }).then((res) => {
          list = fieldListHandle(nodeFields, res.data);
          fieldInfo.value = list;
        });
        break;
      case "pod": {
        getHierachyTopoPodDetail({
          masterIp: node.masterIp,
          namespace: node.namespace,
          podName: node.name,
          sid: node.sid,
          from,
          to,
        }).then((res) => {
          list = fieldListHandle(podFields, res.data);
          fieldInfo.value = list;
        });
        const params = {
          masterIp: node.masterIp,
          namespace: node.namespace,
          podUid: node.attributes.podUid,
          podName: node.name,
        };
        getContainerList(params).then((res) => {
          // setContainerList(res.data || []);
          containerList.value = res.data || [];
          allContainer.value = res.data || [];
        });
        getPodEventData();
        break;
      }
      case "service":
        getHierachyTopoServiceDetail({
          masterIp: node.masterIp,
          namespace: node.namespace,
          serviceName: node.name || node.nameBak,
          from,
          to,
        }).then((res) => {
          list = fieldListHandle(serviceField, res.data);
          fieldInfo.value = list;
        });
        break;
      case "workload": {
        Promise.all([
          getHierachyTopoWorkloadDetail({
            masterIp: node.masterIp,
            namespace: node.namespace,
            workloadName: node.name,
            workloadType: node.attributes.workloadType,
            from,
            to,
          }),
          getK8sYaml({
            masterIp: node.masterIp,
            namespace: node.namespace,
            name: node.name,
            type: node.attributes.workloadType,
          }),
        ]).then((res) => {
          if (Array.isArray(res) && res.length) {

            list = fieldListHandle(workloadFields, res[0].data);
            const label = list.find((item) => item.dataIndex === "labels");
            if (label) {
              label.value = res[1].data.labels;
            }
            fieldInfo.value = list;
          }
          // console.log(list , 'list out of if');

        });
        break;
      }

      default:
        break;
    }
    console.log(list, "field list");

    fieldInfo.value = list;
  };
  const fieldContentStyle = {
    overflow: "hidden",
    textOverflow: "ellipsis",
    whiteSpace: "nowrap",
    display: "inline-block",
  };
  watch(nodeInfo, (newV) => {
    // console.log(newV, "new NodeiNFO");
    getFieldList();
  });
  const containerColumns = [
    {
      title: "名称",
      dataIndex: "name",

    },
    {
      title: "状态",
      dataIndex: "status",
    },
    {
      title: "命名空间",
      dataIndex: "namespace",
    },
    {
      title: "CPU使用量",
      dataIndex: "cpuUsage",
      render: (value) => formatUnit(value, "核"),
      sorter: (a, b) => a.cpuUsage - b.cpuUsage,
    },
    {
      title: "内存使用量",
      dataIndex: "memoryUsage",
      render: (value) => formatUnit(value, "byteMin"),
      sorter: (a, b) => a.memoryUsage - b.memoryUsage,
    },
  ];
  return {
    fieldInfo,
    containerList,
    fieldContentStyle,
    containerColumns,
    filterContainer,
  };
}
